package com.huawei.crm.job;

import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class TestJob implements SchedulingConfigurer {
	private ScheduledTaskRegistrar taskRegistrar;
	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		this.taskRegistrar = taskRegistrar;
		IndexTask1 indexTask = new IndexTask1();
//		indexTask.setType(IndexTask.TaskType.INTERVAL);
		indexTask.setInterval(JobUtil.getInterval(10, TimeUnit.SECONDS));
		addIndexTask(indexTask);
//		indexTask.setFinished(true);
		indexTask.setInterval(JobUtil.getInterval(15, TimeUnit.SECONDS));
	}

	public void addIndexTask(IndexTask indexTask) {
		if (indexTask.getType() == IndexTask.TaskType.CRON) {
			taskRegistrar.scheduleTriggerTask(new TriggerTask(indexTask, getTrigger(indexTask)));
		} else {
			taskRegistrar.scheduleTriggerTask(new TriggerTask(indexTask, getTrigger(indexTask)));
		}
	}

	private static Trigger getTrigger(IndexTask indexTask) {
		return triggerContext -> {
			if (indexTask.isFinished()) {
				return null;
			}
			Trigger trigger;
			if (indexTask.getType() == IndexTask.TaskType.CRON) {
				// 使用CronTrigger触发器，可动态修改cron表达式来操作循环规则
				trigger = new CronTrigger(indexTask.getCronExpress());
			} else {
				// 使用不同的触发器，为设置循环时间的关键，区别于CronTrigger触发器，该触发器可随意设置循环间隔时间，单位为毫秒
				trigger = new PeriodicTrigger(indexTask.getInterval());
			}
			return trigger.nextExecutionTime(triggerContext);
		};
	}

}
